package com.baseproject.datasource.get.procedure;

import android.support.annotation.Nullable;

import com.baseproject.datasource.Repository;
import com.baseproject.util.LogUtils;

import java.util.List;
import java.util.Map;

import rx.Observable;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by hp on 2017/8/17.
 */

public class CommonRemoteDataProcedure extends DataProcedure {

    public CommonRemoteDataProcedure(Class className) {
        super(className);
    }

    @Override
    public <T> Observable<List<T>> getList(Class<T> className) {
        Observable<List<T>> cacheObservable = null;
        List cached = getFromCache(Repository.getInstance().getCacheList());
        if (null != cached && cached.size() > 0) {
            cacheObservable = Observable.from(cached).toList()
                    .doOnNext(new Action1() {
                        @Override
                        public void call(Object o) {
                            LogUtils.d("Repository", "cache data used! className = " + className);
                        }
                    });
        }
        Observable<List<T>> localObservable = cacheObservable != null ? cacheObservable : Repository.getInstance().getListFromLocalDataSource(this, this.getClassName());
        Observable<List<T>> remoteObservable = Repository.getInstance().getListFromRemoteDataSource(CommonRemoteDataProcedure.this,
                CommonRemoteDataProcedure.this.getClassName());
        return Observable.concat(localObservable, remoteObservable)
                .filter(new Func1<List<T>, Boolean>() {
                    @Override
                    public Boolean call(List<T> contentList) {
                        return (null != contentList && contentList.size() > 0);
                    }
                });
    }

    @Nullable
    private  List getFromCache(Map<String, List> cacheList) {
        return cacheList.get(mLocalRequestParams.getUniqueKey());
    }
}
